<template>
  <BKModal
    title="添加用户"
    v-model="visible"
    width="70%"
    height="80%"
  >
    <div class="full-height d-flex-c overflow-hidden">
      <div
        class="d-flex overflow-hidden"
        style="height: calc(100% - 50px);"
      >
        <div
          class="d-flex-c b-r"
          style="width: 300px;"
        >
          <div class="area-title">
            组织机构
          </div>
          <ConfigTree
            ref="tree"
            class="overflow-hidden"
            :has-top="false"
            :configs="treeConfigs"
            :config-tree-props="configTreeProps"
            @nodeClicked="handleNodeClick"
          />
        </div>
        <ConfigGrid
          class="overflow-hidden flex-1"
          ref="grid"
          size="medium"
          :has-toolbar-left="false"
          :has-add="false"
          :has-batch-remove="false"
          :toolbar-config="null"
          :config-form-props="{size:'small'}"
          :condition-form-props="{size: 'small', buttonSize: 'small'}"
          :configs="gridConfigs"
          :after-query="afterQuery"
          row-id="USER_ID"
          :has-pager="false"
          :checkbox-config="{reserve:true}"
          @checkbox-change="handleSelectMember"
          @checkbox-all="handleSelectMember"
        />
      </div>

      <div
        class="b-t p-a-mini ta-c m-h-mini flex-0"
      >
        <el-button
          size="small"
          type="primary"
          :disabled="!newMembers.length"
          @click="$emit('confirm',newMembers)"
        >
          确定
        </el-button>
        <div
          v-show="newMembers.length"
        >
          {{ `当前已选 ${newMembers.length} 人` }}
        </div>
      </div>
    </div>
  </BKModal>
</template>
<script>
export default {
  name: 'AddMember',
  data () {
    return {
      visible: false,
      currentNode: { id: this.$store.state.user.userInfo.DEPT_ID },
      treeConfigs: {
        dictionaryKeys: ['DIC_WATF_B_UP_D'],
        activeNodeKey: this.$store.state.user.userInfo.DEPT_ID,
        includeSelf: true,
        sortKeyProps: { id: 'DEPT_ID', fid: 'PARENT_ID', order: 'ORDER_NUM' },
        hasIcon: false,
        canSwitchBzCode: false,
        appId: 'watf',
        bzCode: 'WATF',
        async: true,
        treeConfigId: 'DEPT_TREE',
        hasAdd: false
      },
      gridConfigs: {
        noParentParam: true,
        noOperation: true,
        isView: false,
        module: '用户',
        appId: 'watf',
        bzCode: 'WATF',
        metaSet: 'WATF_B_SYS_USER',
        defaultQueryParamsProcessor: this.defaultQueryParamsProcessor,
        parentNodeProps: { DEPT_ID: 'id' }
      },
      newMembers: [],
      configTreeProps: {
        nodeParam: this.$store.state.user.userInfo.DEPT_ID
      }
    }
  },
  methods: {
    show () {
      this.visible = true
      this.$nextTick(() => {
        this.$refs.grid.refreshList()
      })
    },
    hide () {
      this.visible = false
      this.$refs.grid.refreshList()
    },
    afterQuery (res) {
      return res.rows
    },
    handleSelectMember () {
      const table = this.$refs.grid.$refs.table
      this.newMembers = table.getCheckboxRecords().concat(table.getCheckboxReserveRecords())
    },
    handleNodeClick (data) {
      this.currentNode = data
      this.$nextTick(() => {
        if (!this.$refs.grid) return
        this.$refs.grid.clearFilter()
        this.$refs.grid.refreshList(this.getDynamicParams(data, this.gridConfigs.parentNodeProps))
      })
    },
    defaultQueryParamsProcessor (params) {
      const methodParams = JSON.parse(params.methodParams)
      const isLeaf = this.currentNode.isLeaf
      const leafIds = isLeaf ? [] : this.levelOrder(this.currentNode)
      methodParams.simpleQueryParam.push({
        field: 'DEPT_ID',
        value: isLeaf ? this.currentNode.id : leafIds.join(','),
        fieldValueRel: isLeaf ? 'like' : 'in'
      })
      methodParams.queryParam = {}
      params.methodParams = JSON.stringify(methodParams)
      return params
    },
    levelOrder (root) {
      const res = []; const queue = []
      queue.push(root)
      if (root === null) {
        return res
      }
      while (queue.length !== 0) {
        const length = queue.length
        for (let i = 0; i < length; i++) {
          const node = queue.shift()
          res.push(node.id)
          for (let n = 0; n < node.children?.length; n++) {
            if (node.children[n]) {
              queue.push(node.children[n])
            }
          }
        }
      }
      return res
    },
    getDynamicParams (data, parentNodeProps) {
      const queryParam = {}
      for (const key in parentNodeProps) {
        if (Object.hasOwnProperty.call(parentNodeProps, key)) {
          const value = parentNodeProps[key]
          queryParam[key] = data[value]
        }
      }
      return queryParam
    }

  }
}
</script>

<style lang="scss" scoped>
.area-title {
  position: relative;
  font-weight: 700;
  color: #424e61;
  height: 40px;
  line-height: 40px;
  padding-left: 10px;
  border-bottom: 1px solid #e8eaec;

  &::before {
    position: absolute;
    content: "";
    left: 0;
    top: 12px;
    width: 4px;
    height: 16px;
    background: #409eff;
    border-radius: 0 3px 3px 0;
  }
}
</style>
